package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreFetcherUtils;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangzq on 14-8-7.
 * 高频彩通用网易163抓取
 */
public abstract class FrequentLotteryDrawFetchWorker163 extends AbstractLotteryDrawFetchWorker {

    protected String siteName = "T_163";
    protected String lotteryScope = "高频彩开奖信息";

    public static Map<LotteryType, String> historyUrlMap = new HashMap<LotteryType, String>();

    static {
        // 好运11选5: HLJ11X5 广东快乐十分: GDKL10  快3: JLK3  快乐8: BJKL8
        //吉林快3
        historyUrlMap.put(LotteryType.JLK3, "http://caipiao.163.com/award/kuai3/");//http://caipiao.163.com/award/kuai3/?gameEn=kuai3&date=20140925   560
        //广东快乐十分
        historyUrlMap.put(LotteryType.GDKL10, "http://caipiao.163.com/award/gdklsf/");//http://caipiao.163.com/award/gdklsf/20140925.html    544
        //好运11选5
        historyUrlMap.put(LotteryType.HLJ11X5, "http://caipiao.163.com/award/hlj11xuan5/");//http://caipiao.163.com/award/hlj11xuan5/20140925.html   569
        //北京快乐8
        historyUrlMap.put(LotteryType.BJKL8, "http://caipiao.163.com/award/kl8/");//http://caipiao.163.com/award/kl8/654966.html   543
    }

    public FrequentLotteryDrawFetchWorker163(LotteryType lotteryType) {
        super(lotteryType);
    }

    @Override
    public LotteryDraw fetchResult(String phase) {
        return fetchResultDetail(phase);
    }

    @Override
    public  LotteryDraw fetchResultDetail(String phase) {
        String lotteryPhase; //页面抓取的彩期号
        String result = "";
        LotteryType lotteryType = this.getLotteryType();
        LotteryDraw lotteryDraw = new LotteryDraw();
        try {
            String url = this.getResultDetailUrl(phase);
            if (StringUtils.isEmpty(url) ) {
                logger.error("未获取得到详情的url信息");
                return null;
            }

            String data = CoreFetcherUtils.URLGet(url, null, CharsetConstant.CHARSET_GBK);
            if (data == null || data.indexOf("404 Not Found") > 0) {
                logger.error("data is null or 404 Not Found");
                return null;
            }
            Parser parser = Parser.createParser(data, CharsetConstant.CHARSET_GBK);
            NodeList tableNodeList;
            try {
                tableNodeList = parser.extractAllNodesThatMatch(new TagNameFilter("table"));
                boolean isNotBreak = true;
                String maxLotteryPhase = "0";
                String maxResult = "";
                if (tableNodeList != null && tableNodeList.size() > 0) {
                    TableTag tableTag = (TableTag)tableNodeList.elementAt(0);
                    if (tableTag == null || tableTag.getRowCount() < 1) {
                        logger.error("未获得高频彩开奖公告信息");
                        return null;
                    }
                    for (int i = 1; isNotBreak && i < tableTag.getRowCount(); i++) {
                        TableColumn[] tableColumn = tableTag.getRow(i).getColumns();
                        for (int j = 0; j < tableColumn.length; j++) {
                            String maxLotteryPhaseTemp = tableColumn[j].getAttribute("data-period");
                            String maxResultTemp;
                            maxResultTemp = tableColumn[j].getAttribute(getResultAttribute());
                            //指定彩期为null，则抓取列表页面的最新彩期数据
                            if (StringUtils.isEmpty(phase)) {
                                //获取有开奖结果的彩期
                                if (StringUtils.isNotEmpty(maxResultTemp) && StringUtils.isNotEmpty(maxLotteryPhaseTemp)) {
                                    if (Long.parseLong(maxLotteryPhaseTemp) > Long.parseLong(maxLotteryPhase)) {
                                        maxLotteryPhase = maxLotteryPhaseTemp;
                                        maxResult = maxResultTemp;
                                    }
                                }
                            } else {
                                //如果传入彩期  获取相应彩期的比赛结果
                                if (StringUtils.isNotEmpty(maxResultTemp) && StringUtils.isNotEmpty(maxLotteryPhaseTemp) && phase.equals(maxLotteryPhaseTemp)) {
                                    maxLotteryPhase = maxLotteryPhaseTemp;
                                    maxResult = maxResultTemp;
                                    isNotBreak = false;
                                    break;
                                }
                            }
                        }
                    }
                }
                lotteryPhase = maxLotteryPhase;
                if (StringUtils.isEmpty(lotteryPhase) || "0".equals(lotteryPhase)) {
                    logger.error("页面抓取的彩期号({})不存在,返回null ", lotteryPhase);
                    return null;
                }
                //指定彩期为null，抓取列表页面的彩期数据
                if (StringUtils.isEmpty(phase)) {
                    phase = lotteryPhase;
                //当前期可写入详细url，以便抓取对应的详细信息
                } else {
                    if (lotteryPhase.equals(phase)) {
                        phase = lotteryPhase;
                    } else {
                        logger.error("指定抓取的彩期号({})与页面抓取的彩期号({})不一致,返回null ", phase, lotteryPhase);
                        return null;
                    }
                }
                if (StringUtils.isNotEmpty(maxResult)) {
                    result = CoreFetcherUtils.mergeStringArray(maxResult.split(" "), ",");
                }
                if (StringUtils.isEmpty(result)) {
                    logger.error("未获取到开奖结果 ", result);
                    return null;
                }
            } catch (ParserException e2) {
                logger.error("连接错误==", e2);
                return null;
            }
            lotteryDraw.setLotteryType(lotteryType);
            lotteryDraw.setPhase(phase);
            lotteryDraw.setResult(result);
            if (StringUtils.isEmpty(lotteryDraw.getPhase())) {
                logger.error("未抓取到相应的开奖结果");
                return null;
            }
        } catch (Exception e) {
            logger.error("抓取开奖详情出现异常");
            logger.error(e.getMessage(), e);
            return null;
        }
        return lotteryDraw;
    }

    @Override
    abstract protected String getResultDetailUrl(String phase);

    @Override
    protected String getResultUrl(String phase) {
        return null;
    }

    abstract protected String getResultAttribute();

}
